package com.intelligent.controller;

import com.intelligent.entity.Department;
import com.intelligent.entity.User;
import com.intelligent.service.DepartmentService;
import com.intelligent.utils.Result;
import com.intelligent.feign.UserApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

@RestController
@RequestMapping("/dept")
public class DepartmentController2 {
    @Autowired
    DepartmentService departmentService;
    @Autowired
    UserApi userApi;

    @GetMapping
    public Result<List<Department>> list() {
        return Result.success(departmentService.list());
    }

    @GetMapping("/byId")
    public Result<Department> getById(@RequestParam("id") Long id) {
        return Result.success(departmentService.getById(id));
    }

    @PostMapping
    public Result<Long> add(@RequestBody Department department) {
        // 后端生成部门编号：BM001、BM002 ...（忽略前端传入的编号）
        department.setDepartmentCode(nextDeptCode());
        departmentService.save(department);
        return Result.success(department.getDepartmentId());
    }

    @PutMapping
    public Result<Void> update(@RequestBody Department department) {
        departmentService.updateById(department);
        return Result.success();
    }

    @DeleteMapping
    public Result<Void> delete(@RequestParam("id") Long id) {
        departmentService.removeById(id);
        return Result.success();
    }

    // 仅四个条件：pageNum / pageSize / keyword / status（GET 查询串）
    @GetMapping("/page")
    public Result<Map<String, Object>> page(
            @RequestParam(value = "pageNum", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "status", required = false) Integer status) {
        int pn = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        int ps = (pageSize == null || pageSize < 1) ? 10 : Math.min(pageSize, 200);

        Page<Department> page = new Page<>(pn, ps);
        LambdaQueryWrapper<Department> qw = new LambdaQueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            qw.and(w -> w.like(Department::getDepartmentCode, keyword)
                    .or().like(Department::getDepartmentName, keyword));
        }
        if (status != null) {
            qw.eq(Department::getStatus, status);
        }

        departmentService.page(page, qw);

        // 填充负责人姓名
        for (Department d : page.getRecords()) {
            try {
                if (d.getUId() != null) {
                    User u = userApi.getById(d.getUId());
                    if (u != null) {
                        d.setLeaderName(u.getRealName() != null ? u.getRealName() : u.getUsername());
                    }
                }
            } catch (Exception e) {
                // 可按需记录日志
            }
        }

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("records", page.getRecords());
        return Result.success(data);
    }

    // 仅四个条件：pageNum / pageSize / keyword / status（POST JSON）
    @PostMapping("/page")
    public Result<Map<String, Object>> pageByBody(@RequestBody Map<String, Object> body) {
        Integer pageNum = body.get("pageNum") instanceof Number ? ((Number) body.get("pageNum")).intValue() : null;
        Integer pageSize = body.get("pageSize") instanceof Number ? ((Number) body.get("pageSize")).intValue() : null;
        String keyword = body.get("keyword") == null ? null : String.valueOf(body.get("keyword"));
        Integer status = body.get("status") instanceof Number ? ((Number) body.get("status")).intValue() : null;
        return page(pageNum, pageSize, keyword, status);
    }

    // 生成下一个部门编号：BM001、BM002、...
    private String nextDeptCode() {
        final String prefix = "BM";
        Department last = departmentService.lambdaQuery()
                .select(Department::getDepartmentCode)
                .likeRight(Department::getDepartmentCode, prefix)
                .orderByDesc(Department::getDepartmentCode)
                .last("limit 1")
                .one();
        int next = 1;
        if (last != null && last.getDepartmentCode() != null) {
            String code = last.getDepartmentCode();
            Matcher m = Pattern.compile("^" + prefix + "(\\d+)$").matcher(code);
            if (m.find()) {
                next = Integer.parseInt(m.group(1)) + 1;
            }
        }
        return String.format(prefix + "%03d", next);
    }
}
